﻿using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity.InterceptionExtension;
using Tools.Common.UnitOfWork.Contracts;
using Web.App.Infrastructure.ApplicationMessages.Contracts;
using Web.App.Infrastructure.ApplicationMessages.Implementation;

namespace Web.App.Infrastructure.CrossCuttingConcerns.Handlers
{
    public class TransactionHandler : ICallHandler
    {
        private IUoWContainer uowContainer;
        private IDomainMessage domainMessage;

        public TransactionHandler(IUoWContainer uowContainer)
        {
            this.uowContainer = uowContainer;

        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var transaction = uowContainer.Current.BeginTransaction();
            IMethodReturn methodReturn = null; 
            
            try
            {
                methodReturn = getNext()(input, getNext);
                transaction.Commit();

            }
            catch (Exception)
            {
                domainMessage = new FailureMessage(
                    new List<IFailure> { new Failure(null, "PERSISTENCE_FAILED", "", "") }, this.GetType().ToString(),
                    "Handle", "Neuregistrierung konnte nicht gespeichert werden");
                transaction.Rollback();

            }
            finally
            {
                transaction.Dispose();
            }

            (methodReturn.ReturnValue as IResponseMessage).DomainMessage = domainMessage;

            return methodReturn;


        }

        public int Order
        {
            get { return 1; }
            set {  }
        }
    }
}
